package com.hoyo.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * 网络链接工具类
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * 
 * @version 1.0
 * @author 龚文伟
 * @date 2017年1月25日
 */
public class HttpUrlConnectionUtils {
	
	private HttpUrlConnectionUtils(){}

	/**
	 * 设置请求参数并打开连接
	 * 
	 * @param url
	 *            请求地址
	 * @param method
	 *            请求方法
	 * @param args
	 *            请求参数<K,V>
	 * @return
	 * @throws Exception
	 */
	public static byte[] openConnection(String url, String method, Map<String, String> headers,  Map<String, String> args) throws Exception {

		HttpURLConnection conn = null;
		InputStream is = null;
		try {
			boolean isPost = false;
			String reqBody = "";
			if (args != null) {
				Set<Entry<String, String>> argsSet = args.entrySet();
				if ("GET".equalsIgnoreCase(method)) {
					url = patchUrl(url, argsSet);
				} else if ("POST".equalsIgnoreCase(method)) {
					reqBody = patchRequestBody(argsSet);
				} else {
					throw new IllegalArgumentException("only recieve get or post type, illegal type:" + method);
				}
			}
			System.out.println(url);
			URL u = new URL(url);
			conn = (HttpURLConnection) u.openConnection();
			conn.setRequestMethod(method);
			if(headers!=null){
				Set<Entry<String, String>> headSet = headers.entrySet();
				for (Entry<String, String> entry : headSet) {
					conn.setRequestProperty(entry.getKey(), entry.getValue());
				}
			}
			if (isPost) {
				conn.setDoOutput(true);
				conn.getOutputStream().write(reqBody.getBytes());
			}
			is = conn.getInputStream();

			return readInput(is);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(is!=null){
				is.close();
			}
			if(conn!=null){
				conn.disconnect();
			}
		}

		return null;
	}
	
	public static byte[] openConnection(String url, String method, Map<String, Object> headers,  String body) throws Exception {

		HttpURLConnection conn = null;
		InputStream is = null;
		try {
			System.out.println(url);
			URL u = new URL(url);
			conn = (HttpURLConnection) u.openConnection();
			conn.setRequestMethod(method);
			if(headers!=null){
				Set<Entry<String, Object>> headSet = headers.entrySet();
				for (Entry<String, Object> entry : headSet) {
					System.out.println(entry.getValue().toString());
					conn.setRequestProperty(entry.getKey(), entry.getValue().toString());
				}
			}
			if ("POST".equalsIgnoreCase(method)) {
				conn.setDoOutput(true);
				conn.getOutputStream().write(body.getBytes());
			}
			is = conn.getInputStream();

			return readInput(is);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(is!=null){
				is.close();
			}
			if(conn!=null){
				conn.disconnect();
			}
		}

		return null;
	}

	/**
	 * 使用POST方式打开连接，并且请求数据为json格式
	 * @param url
	 * @param json
	 * @return
	 */
	public static byte[] openConnWithJSON(String url, String json) {
		HttpURLConnection conn = null;
		InputStream is = null;
		try {
			URL u = new URL(url);
			conn = (HttpURLConnection) u.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.getOutputStream().write(json.getBytes());

			is = conn.getInputStream();

			return readInput(is);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (conn != null) {
				conn.disconnect();
			}
		}

		return null;
	}

	/**
	 * 拼凑请求体信息
	 * 
	 * @param argsSet
	 *            请求参数的键值对集合
	 * @return
	 */
	public static String patchRequestBody(Set<Entry<String, String>> argsSet) {

		StringBuilder builder = new StringBuilder();
		for (Entry<String, String> argEntry : argsSet) {
			builder.append(argEntry.getKey() + "=" + argEntry.getValue() + "&");
		}
		String body = builder.toString();

		return body.substring(0, body.length() - 1);
	}

	/**
	 * 对于Get请求方式，如果带有请求参数，则进行url请求参数的拼凑，
	 * 
	 * @param url
	 *            请求地址
	 * @param argsSet
	 *            请求参数键值对集合
	 * @return url 拼凑后的请求地址
	 */
	private static String patchUrl(String url, Set<Entry<String, String>> argsSet) {

		return url + "?" + patchRequestBody(argsSet);
	}

	private static byte[] readInput(InputStream is) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			int len = -1;
			byte[] buffer = new byte[1024];
			while ((len = is.read(buffer, 0, buffer.length)) != -1) {
				baos.write(buffer, 0, len);
			}
			baos.close();

			return baos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	public static void main(String[] args) {
		/*String url = "http://v2.m21.com/m21-server/admin/task/tasks";
		Map<String, String> map = new HashMap<String, String>();
		map.put("longitude_tx", "");
		map.put("latitude_tx", "23.020536");
		try {
			openConnection(url, "post", map);
		} catch (Exception e) {
			e.printStackTrace();
		}*/
	}
}
